package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.CrmRedisKeys;
import cc.linker.steplink.crm.commons.constant.OssConstant;
import cc.linker.steplink.crm.commons.constant.TlPayConstant;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.OverViewInfoDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.acs.ExternalOrderService;
import cc.linker.steplink.crm.merchanth5.service.acs.ProtectRecordService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.service.redis.GoodsService;
import cc.linker.steplink.crm.merchanth5.service.redis.MerchantService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@EnableAsync
@Service
public class MaiBaoLaService {
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ProtectRecordService protectRecordService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private ExternalOrderService externalOrderService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private OverViewInfoDao overViewInfoDao;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${spring.profiles.active}")
    private String profiles;

    public void saveGoods(Map<String, Object> map) throws GlobalException {
        if (!map.containsKey("customerId") || !map.containsKey("orgId")) {
            throw GlobalException.build("获取用户信息异常");
        }
        if (map.containsKey("rebate")) {
            try {
                Integer rebate = (Integer) map.get("rebate");
            } catch (Exception e) {
                throw GlobalException.build("返利不正确");
            }
        } else {
            throw GlobalException.build("请填写返利");
        }
        String customerId = (String) map.get("customerId");
        int i = maiBaoLaDao.countCustomerId(customerId);
        Integer quota = maiBaoLaDao.getQuotaByCustomerId(customerId);
        if (i >= quota && !map.containsKey("goodsId") && quota != -1) {
            throw GlobalException.build("商品超出限制");
        } else if (map.containsKey("goodsId")) {
            String goodsId = map.get("goodsId").toString();
            String banned = maiBaoLaDao.getGoodsBannedByGoodsId(Long.valueOf(goodsId));
            if ("1".equals(banned)) {
                throw GlobalException.build("此商品被封禁");
            }
            maiBaoLaDao.updateGoods(map);
        } else if (i < quota || quota == -1) {
            maiBaoLaDao.insertGoods(map);
            // 更新销售员状态 有商品
            maiBaoLaDao.updateSaler(customerId);
        }
    }

    public Map getGoods(String customerId, String goodsId, String orgId, boolean flag, String source) throws GlobalException {
        if (StringUtils.isEmpty(customerId) && !flag) {
            throw GlobalException.build("用户信息获取失败");
        }
        if (StringUtils.isEmpty(goodsId)) {
            // 获取自己的商品
            throw GlobalException.build("缺少参数");
        }
        // 获取商品id对应的商品
        Map<String, Object> goods = goodsService.getGoodsInfo(goodsId);
        if(!StringUtils.isEmpty(goods.get("mallsGoodsId"))){
            Map<String, Object> mallsGoods = goodsService.getGoodsInfo(goods.get("mallsGoodsId").toString());
            goods.put("malls",mallsGoods.get("malls"));
        }

        // 判断删除或者封禁
        if (flag) {
            // 懂小姐
            if (goods.get("isDelete") != null && "1".equals(goods.get("isDelete").toString())) {
                // 商品已被删除
                throw GlobalException.build("商品已被删除");
            }
        } else {
            // StepLink
            this.judgeDeleteOrBanned(goods);
        }
        if (flag && "dong".equals(source) && goods.get("dongGoodsStatus") != null && Integer.valueOf(goods.get("dongGoodsStatus").toString()) != 1) {
            throw GlobalException.build("商品已下架");
        }
        goods = this.getGoodsExtInfo(goods, customerId, goodsId, orgId);
        return goods;
    }

    //通过商品ID获取商品信息
    public Map getGoodsInfo(String customerId, String goodsId, String orgId) throws GlobalException {
        if (StringUtils.isEmpty(goodsId)) {
            throw GlobalException.build("缺少参数");
        }
        Map<String, Object> goodsInfo = goodsService.getGoodsInfo(goodsId);
        this.judgeDeleteOrBanned(goodsInfo);
        goodsInfo = this.getGoodsExtInfo(goodsInfo, customerId, goodsId, orgId);
        if(!StringUtils.isEmpty(goodsInfo.get("isSeckill")) && "1".equals(goodsInfo.get("isSeckill").toString())){
            this.getKillThings(goodsInfo);
        }
        return goodsInfo;
    }

    public void getKillThings(Map mallGoods){
        try {
            Map<String, Object> seckillMap;
            String seckillMapStr = stringRedisTemplate.opsForValue().get("goodsSeckill:" + mallGoods.get("goodsId").toString());
            if (StringUtils.isEmpty(seckillMapStr)) {
                seckillMap =  mallDao.getSeckillByGoodsId(mallGoods.get("goodsId").toString());
                stringRedisTemplate.opsForValue().set("goodsSeckill:"  + mallGoods.get("goodsId").toString(), JSON.toJSONString(seckillMap, SerializerFeature.WriteMapNullValue),15, TimeUnit.SECONDS);
            }else {
                seckillMap = (Map<String, Object>) JSON.parse(seckillMapStr);
                SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                seckillMap.put("startTime",df2.format(new Date(Long.parseLong(seckillMap.get("startTime").toString()))));
                seckillMap.put("endTime",df2.format(new Date(Long.parseLong(seckillMap.get("endTime").toString()))));
            }
            if(seckillMap!=null && seckillMap.size()>0){
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1=df.parse(startTime);
                Date sd2=df.parse(endTime);
                Date nowDate = new Date();
                mallGoods.put("seckillAllSecond",(sd2.getTime()-sd1.getTime())/1000);
                if(sd1.after(nowDate)){
                    //未开始
                    mallGoods.put("seckillStatus",0);
                    mallGoods.put("seckillSecond",(sd1.getTime()-nowDate.getTime())/1000);
                }else if(nowDate.after(sd2)){
                    //已结束
                    mallGoods.put("seckillStatus",2);
                    mallGoods.put("seckillSecond",(nowDate.getTime()-sd2.getTime())/1000);
                }else {
                    //进行中
                    mallGoods.put("seckillStatus",1);
                    mallGoods.put("seckillSecond",(sd2.getTime()-nowDate.getTime())/1000);
                }
                if(seckillMap.get("seckillMultiole") != null){
                    mallGoods.put("seckillMultiole",Double.valueOf(seckillMap.get("seckillMultiole").toString()));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取商品的扩展数据
    private  Map<String,Object> getGoodsExtInfo(Map<String,Object> goods,String customerId,String goodsId,  String orgId) {
        String videoResId = (String) goods.get("videoResId");
        String videoCover = (String) goods.get("videoCover");
        if (StringUtils.isEmpty(videoCover) && !StringUtils.isEmpty(videoResId)) {
            String cover = this.getVideoCoverByVideoResId(videoResId);
            goods.put("videoCover", cover);
        }
        String belongId = (String) goods.get("belongId");
        String enterpriseName;
        if (!StringUtils.isEmpty(belongId)) {
            enterpriseName = maiBaoLaDao.getEnterpriseNameByCustomerId(belongId);
        } else {
            if (StringUtils.isEmpty(orgId)) {
                orgId = (String) goods.get("orgId");
            }
            enterpriseName = maiBaoLaDao.getEnterpriseNameByOrgId(orgId);
        }
        if (enterpriseName == null) {
            enterpriseName = "";
        }
        goods.put("enterpriseName", enterpriseName);
        if (customerId.equals(belongId)) {
            goods.put("mine", true);
        } else {
            goods.put("mine", false);
        }
        String filePath = redisTemplate.opsForValue().get("idp_sourceImg_" + goodsId);
        if (StringUtil.isNotEmpty(filePath)) {
            goods.put("goodsPreview", filePath);
        } else {
            goods.put("goodsPreview", null);
        }
        if(!StringUtils.isEmpty(goods.get("freightTemplateId"))){
            String freightTemplateId = goods.get("freightTemplateId").toString();
            goods.put("goodsFreight",maiBaoLaDao.getLeastTemplateFee(freightTemplateId));
        }
        return goods;
    }
    /**
     * 根据商品Id查出所对应的赠品id
     *
     * @param goodsId 商品id
     */
    public List<Map<String, Object>> getExerciseByGoodsId(String goodsId) {
        List<Map<String, Object>> exerciseList = maiBaoLaDao.getExerciseByGoodsId(goodsId);
        if (exerciseList == null || exerciseList.size() == 0) {
            return new ArrayList<>();
        }
        // 相同商品去重
        List<String> strings = new ArrayList<>();
        // 体检券去重
        boolean dong = false;
        Iterator<Map<String, Object>> iterator = exerciseList.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
            Integer giftType = (Integer) map.get("giftType");
            String giftContent = (String) map.get("giftContent");
            if (giftType == 1) {
                if (strings.contains(giftContent)) {
                    iterator.remove();
                    continue;
                }
                strings.add(giftContent);
                Map<String, Object> goods = new HashMap<>();
               Integer goodsType = this.maiBaoLaDao.getGoodsType(giftContent);
               //3 内容 4专栏
               if(goodsType.equals(3)){
                   goods = goodsService.getContentGoodsInfo(giftContent);
               }else{
                   goods = goodsService.getCloumnGoodsInfo("",giftContent);
               }
                String[] row = {"goodsName", "goodsCover", "promotion", "goodsType"};
                for (String s : row) {
                    map.put(s, goods.get(s));
                }
                if(goodsType.equals(4)){
                    map.put("goodsCover",goods.get("columnCover"));
                }
            } else if (giftType == 2) {
                // 2 懂小姐赠品
                if (dong) {
                    iterator.remove();
                    continue;
                }
                dong = true;
                map.put("promotion", "");
                map.put("goodsType", "");
                map.put("goodsCover", "");
                map.put("goodsName", "线上体检");
            }
        }
        return exerciseList;
    }

    private String getVideoCoverByVideoResId(String resId) {
        Map<String, Object> params = new HashMap<>();
        params.put("ResId", resId);
        String url = systemProperties.getMaterialCenter() + OssConstant.OSS_INFO;
        String result;
        try {
            result = httpService.doPost(url, JSON.toJSONString(params), OssConstant.JSON);
        } catch (Exception e) {
            LOGGER.error("素材中心调用异常", e);
            return null;
        }
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        Integer code = jsonObject.getInteger("Code");
        if (code == null || code != 200) {
            LOGGER.info("getVideoCoverByVideoResId===result===[{}]", result);
            return null;
        }
        return jsonObject.getString("Thumbnail");
    }

    /**
     * 判断删除或者封禁
     *
     * @param param map中需要isDelete、banned、belongId 三个字段
     */
    public void judgeDeleteOrBanned(Map<String, Object> param) {
        if (param == null) {
            throw GlobalException.notFound();
        }
        if (param.get("isDelete") != null && "1".equals(param.get("isDelete").toString())) {
            // 商品已被删除
            throw GlobalException.notFound((String) param.get("belongId"));
        }
        if (param.get("banned") != null && "1".equals(param.get("banned"))) {
            // 商品被封禁
            throw GlobalException.notFound((String) param.get("belongId"));
        }
    }

    /**
     * 实体类判断，其他同上
     */
    public void judgeDeleteOrBanned(Object o) {
        if (o == null) {
            throw GlobalException.notFound();
        }
        Map<String, Object> map = BeanMapUtils.beanToMap(o);
        this.judgeDeleteOrBanned(map);
    }

    public void updateStatus(String customerId, String goodsId) throws GlobalException {
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("用户信息获取失败");
        }
        int i = maiBaoLaDao.countCustomerId(customerId);
        if (i == 0) {
            throw GlobalException.build("用户无商品");
        }
        if (goodsId == null) {
            maiBaoLaDao.updateGoodsStatusByCustomerId(customerId);
        } else {
            String banned = maiBaoLaDao.getGoodsBannedByGoodsId(Long.valueOf(goodsId));
            if ("1".equals(banned)) {
                throw GlobalException.build("此商品被封禁");
            }
            maiBaoLaDao.updateGoodsStatusByGoodsId(goodsId);
            maiBaoLaDao.cleanGoodsBindArticle(goodsId);
        }
    }

    public Object getGoodsList(String customerId) {
        return maiBaoLaDao.getGoodsListByCustomerId(customerId);
    }

    public Object getRecommenderInfo(String customerId) {
        String pid = maiBaoLaDao.getPidByCid(customerId);
        if (StringUtils.isEmpty(pid)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();
        String name = maiBaoLaDao.getNameByCustomerId(pid);
        map.put("name", name);
        String rebateRf = maiBaoLaDao.getRebateRfByCid(pid);
        map.put("rebateRf", rebateRf);
        return map;
    }

    public Object getSharerInfoAfterGoods(String orderSn) {
        String pid = maiBaoLaDao.getPidByOrderId(orderSn);
        if (StringUtils.isEmpty(pid)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();
        String name = maiBaoLaDao.getNameByCustomerId(pid);
        map.put("name", name);
        String rebateRf = maiBaoLaDao.getRebateByCid(pid);
        map.put("rebateRf", rebateRf);
        return map;
    }

    /*
    * 获取商家信息
    * param goodsId 商品ID
    * */
    public Map<String, Object> getMerchantDetailById(String goodsId) {
        Map<String, Object> goodsInfo =  goodsService.getGoodsInfoNotWriteRedis(goodsId);
        if (goodsInfo == null) {
            String originalGoodsId = maiBaoLaDao.getOriginalGoodsId(goodsId);
            goodsInfo =  goodsService.getGoodsInfoNotWriteRedis(originalGoodsId);
            if(goodsInfo == null){
                throw GlobalException.build("商家信息不存在");
            }
        }
        String belongId = goodsInfo.containsKey("belongId")&&  goodsInfo.get("belongId") !=null ? goodsInfo.get("belongId").toString() : "";
        return merchantService.getMerchantDetail(belongId, goodsInfo.get("orgId").toString());
    }

    public Map<String, Object> serviceInfo(Map<String, Object> param) {
        Map<String, Object> result = maiBaoLaDao.serviceInfo(param);
        if (null == result) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("servicePhone", "");
            temp.put("serviceMobilePhone", "");
            return temp;
        } else {
            return result;
        }

    }

    public Map<String, Object> getBelongByGoodsId(String goodsId) {
        return maiBaoLaDao.getBelongByGoodsId(goodsId);
    }


    /**
     * 获取 应用别名
     *
     * @param orgId
     * @return
     */
    public String getAlias(String orgId) {
        Integer payMode = maiBaoLaDao.getPayModeByOrgId(orgId);
        if (payMode == 1) {
            return "";
        } else if(payMode == 3){
            // 联汇模式 获取联汇支付模式的应用别名
            return maiBaoLaDao.getAliasByLinker();
        }
        String alias = maiBaoLaDao.getAlias(orgId);
        if (StringUtils.isEmpty(alias)) {
            throw GlobalException.build("请先设置应用别名");
        }
        return alias;
    }

    /**
     * 判断h5是否已开户
     * 开户 发生验证码  绑定支付标识
     *
     * @param param 参数
     *              customerID
     *              openId
     *              orgId
     * @return
     */
    public Integer checkCustomerAccount(Map<String, Object> param, Integer payMode) {
        String customerId = (String) param.get("customerId");
        String keys = "checkCustomerAccount" + customerId;
        String checkLock = redisTemplate.opsForValue().get(keys);
        if(StringUtil.isNotEmpty(checkLock)){
            return 0;
        }
        redisTemplate.opsForValue().set(keys,"1",10, TimeUnit.SECONDS);
        LOGGER.info("checkCustomerAccount: " + JSON.toJSONString(param));
        String acctType = StringUtils.isEmpty(param.get("acctType"))?"WX":param.get("acctType").toString();
        param.put("acctType", acctType);
        String alias = "";
        if(payMode == 3){
            alias = this.getAliasByLinker();
        }
        if(payMode == 2){
            alias = this.getAlias(param.get("orgId").toString());
        }
        param.put("clintType",alias);
        // 判断h5用户 开户
        Integer cCount = maiBaoLaDao.checkCustomerAccount(param);
        if (cCount < 1 || param.containsKey("customerPhone")) {
            // 调用个人H5开户
            param.put("source", "1");
            LOGGER.info("createMember: " + JSON.toJSONString(param));
            createMember(param);
        } else if(!StringUtils.isEmpty(param.get("openId")) && !"2".equals(param.get("orderSource"))) {
            //app 用户不用绑支付标识
            // 判断 用户绑定支付标识
            int count = maiBaoLaDao.checkCustomerAccountIden(param);
            LOGGER.info("用户绑定支付标识====count===>"+count);
            if (count < 1) {
                // 调用 用户绑定支付标识
                applyBindAcct(param);
            }else {
                cCount = 1;
            }
        }
        if(cCount>0){
            cCount = 1;
        }
        redisTemplate.delete(keys);
        return  cCount;
    }

    /**
     * 选择某个机构下所有个人 开户操作
     * @param orgId
     */
    @Async
    public void orgCreateMember(String orgId)
    {
        // 获取当前机构下所有的可用账户
        List<Map<String,Object>> list = maiBaoLaDao.getCustomerInfoByOrgId(orgId);
        list.forEach(x->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, Object> accountParam = new HashMap<>();
            accountParam.put("customerId", x.get("customerId").toString());
            accountParam.put("openId", x.get("openId").toString());
            accountParam.put("source", "1");
            accountParam.put("clintType", getAlias(orgId));
            accountParam.put("acctType", "WX");
            try {
                LOGGER.info("createMemberParam: " + JSON.toJSONString(accountParam));
                String result = httpService.doPost(wcPayProperties.getAcsurl() + TlPayConstant.USER_CREATE_MEMBER, JSON.toJSONString(accountParam), WcPayConstant.JSON);
                LOGGER.info("createMemberResult: " + result);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        });
    }

    /**
     * 个人H5开户
     *
     * @param map
     */
    private void createMember(Map<String, Object> map) {
        if(!"dev".equals(profiles)){
            try {
                String result = httpService.doPost(wcPayProperties.getAcsurl() + TlPayConstant.USER_CREATE_MEMBER, JSON.toJSONString(map), WcPayConstant.JSON);
                LOGGER.info("个人H5开户 createMember："+result);
                if (null != result) {
                    JSONObject object = JSONObject.parseObject(result);
                    if (("200").equals(object.getString("code"))) {
                        String statusCode = object.getJSONObject("data").getString("status");
                        if ("20".equals(statusCode)) {
                            throw GlobalException.build("个人H5开户处理中");
                        } else if ("40".equals(statusCode)) {
                            throw GlobalException.build("个人H5开户失败！");
                        }
                    } else {
                        throw GlobalException.build(object.getString("message"));
                    }
                } else {
                    throw GlobalException.build("请求个人H5开户失败");
                }
            } catch (Exception e) {
                throw GlobalException.build("个人H5开户失败");
            }
        }
    }

    /**
     * 用户绑定支付标识
     *
     * @param map
     */
    private void applyBindAcct(Map<String, Object> map) {
        String result;
        try {
            result = httpService.doPost(wcPayProperties.getAcsurl() + TlPayConstant.USER_APPLY_BIND_ACCT, JSON.toJSONString(map), WcPayConstant.JSON);
            LOGGER.info("用户绑定支付标识结果===" + result);
        } catch (Exception e) {
            throw GlobalException.build("用户绑定支付标识失败");
        }
        if (null != result) {
            JSONObject object = JSONObject.parseObject(result);
            if (("200").equals(object.getString("code"))) {
                String statusCode = object.getJSONObject("data").getString("status");
                if ("20".equals(statusCode)) {
                    throw GlobalException.build("用户绑定支付标识处理中");
                } else if ("40".equals(statusCode)) {
                    throw GlobalException.build("用户绑定支付标识失败！");
                }
            } else {
                throw GlobalException.build(object.getString("msg"));
            }
        } else {
            throw GlobalException.build("请求用户绑定支付标识失败");
        }

    }

    public Map<String, Object> getShopName(String orgId, String customerId, String type) {
        return maiBaoLaDao.getShopName(orgId, customerId, type);
    }


    public Map<String, Object> getCheckSwitch(String orgId) {
        Map<String, Object> res = maiBaoLaDao.getCheckSwitch(orgId);
        if(StringUtils.isEmpty(res)){
            Map<String,Object> result = new HashMap<>();
            result.put("agentCheck",0);
            result.put("promoterCheck",0);
            return result;
        }else{
            return res;
        }
    }

    public void addCheckInfo(Map<String, Object> map) {
        maiBaoLaDao.addCheckInfo(map);
    }

    public List<Map<String, Object>> checkList(Map<String, Object> params) {
        return maiBaoLaDao.checkList(params);
    }

    public void checkInfo(Map<String, Object> params) {
        String orgId = params.get("orgId").toString();
        // 更新状态
        maiBaoLaDao.checkInfo(params);
        try {
            // 发送信息
            String businessType = "9008";
            if ("2".equals(params.get("status").toString())) {
                // 打回
                businessType = "9009";
            }
            String phone = maiBaoLaDao.getBindPhoneById(params.get("id").toString());
            Map<String, Object> nvps = new HashMap<>();
            nvps.put("businessType", businessType);
            nvps.put("mobilNumber", phone);
            String publicName = maiBaoLaDao.getPublicNameByOrgId(params.get("orgId").toString());
            nvps.put("params", "{name=" + publicName + "公众号}");
            String result = smsService.sendMsg(orgId, nvps);
            LOGGER.info("审核短信发送结果===" + result);
        } catch (Exception e) {
            LOGGER.info("短信网关错误===" + e);
        }
    }

    public Map<String, Object> refundInfo(Map<String, Object> param) {
        // 退款信息
        Map<String, Object> result = maiBaoLaDao.refundInfo(param);
        if (result == null) {
            LOGGER.info("退款信息参数--》"+JSON.toJSONString(param));
            throw GlobalException.build("无权限查看该退款详情");
        }
        Integer refundAmount = Integer.parseInt(result.get("refundAmount").toString());
        Integer shippingFee = Integer.parseInt(result.get("shippingFee").toString());
        Integer goodsReturnnum = Integer.parseInt(result.get("goodsReturnnum").toString());
        Integer couponAmount = Integer.parseInt(result.get("couponAmount").toString());
        refundAmount = refundAmount * goodsReturnnum + shippingFee-couponAmount;
        result.put("refundAmount", refundAmount);
        // 获取店铺的退货信息
        String orgId = param.get("orgId").toString();
        String belongId = result.get("belongId").toString();
        String mallsOrgId = "";
        String mallsBelongId = "";
        if(!StringUtils.isEmpty(result.get("mallsGoodsId"))){
            Long mallsGoodsId = Long.valueOf(result.get("mallsGoodsId").toString());
            mallsOrgId = orgId = purchaseProcessDao.getOrgIdByGoodsId(mallsGoodsId);
            mallsBelongId = belongId =  purchaseProcessDao.getBelongIdByGoodsId(mallsGoodsId);
        }
        result.put("mallsOrgId",mallsOrgId);
        result.put("mallsBelongId",mallsBelongId);
        Map<String, Object> temp = maiBaoLaDao.getRefundByOrgIdAndCustomerId(orgId, belongId);
        result.putAll(temp);
        // 获取退款实际到账情况
        Integer refundAmountStatus = maiBaoLaDao.getRefundAmountStatus(param);
        result.put("refundAmountStatus",refundAmountStatus);
        return result;
    }

    public void addRefundExpress(Map<String, Object> map) {
        String expressImages = "";
        List list = (List) map.get("expressImages");
        if (list.size() > 0) {
            expressImages = JSONArray.toJSONString(map.get("expressImages"));
        }
        map.put("expressImages", expressImages);
        maiBaoLaDao.addRefundExpress(map);
        // 添加协商记录
        Map<String, Object> param = new HashMap<>();
        param.put("recId", map.get("recId"));
        param.put("protectCode", map.get("protectCode"));
        String phone = maiBaoLaDao.getRefundPhoneByRecId(map.get("recId").toString());
        String consultContent = "物流名称：" + map.get("expressName").toString() + "\n" +
                "物流编号：" + map.get("expressCode").toString() + "\n" +
                "退款说明：" + map.get("expressRemark").toString() + "\n" +
                "联系电话：" + phone;
        param.put("consultStatus", "已退货,等待商家确认收货");
        param.put("consultContent", consultContent);
        param.put("consultImages", expressImages);
        param.put("consultObj", 1);
        maiBaoLaDao.addConsult(param);
        try {
            // 调用江苏台erp退款发货接口
            if (map.get("recId") != null) {
                externalOrderService.synchronizationRefund(Long.valueOf(map.get("recId").toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, Object> getRefundDetail(Map<String, Object> params) {
        Map<String, Object> result = maiBaoLaDao.getRefundDetail(params);
        if (!StringUtils.isEmpty(result.get("goodsPrice"))) {
            result.put("goodsPrice", NumberUtils.fenToYuan(Long.parseLong(result.get("goodsPrice").toString())));
        }
        if (!StringUtils.isEmpty(result.get("refundAmount"))) {
            result.put("refundAmount", NumberUtils.fenToYuan(Long.parseLong(result.get("refundAmount").toString())));
        }
        return result;
    }

    public void addConsult(Map<String, Object> map) {
        Map<String, Object> param = new HashMap<>();
        param.put("recId", map.get("recId"));
        param.put("protectCode", map.get("protectCode"));
        param.put("consultStatus", map.get("consultStatus"));
        param.put("consultContent", map.get("consultContent"));
        String consultImages = "";
        if (!StringUtils.isEmpty(map.get("consultImages"))) {
            consultImages = JSONArray.toJSONString(map.get("consultImages"));
        }
        param.put("consultImages", consultImages);
        param.put("consultObj", 1);
        maiBaoLaDao.addConsult(param);
    }

    public Map<String, Object> consultList(Map<String, Object> param) {
        Map<String, Object> temp = new HashMap<>();
        String goodsId = maiBaoLaDao.getGoodsIdByProtectCode(param.get("protectCode").toString());
        temp.put("goodsId", goodsId);
        List<Map<String, Object>> result = maiBaoLaDao.consultList(param);
        result.forEach(x -> {
                    if (!StringUtils.isEmpty(x.get("consultImages"))) {
                        x.put("consultImages", JSON.parseArray(x.get("consultImages").toString()));
                    }
                }
        );
        temp.put("list", result);
        return temp;
    }

    public void cancelRefund(Map<String, Object> param) {
        Long recId = Long.parseLong(param.get("recId").toString());
        Map<String, Object> orderInfo = maiBaoLaDao.getOrderInfoByRecId(recId);
        String orderSn = orderInfo.get("orderSn").toString();
        String orgId = param.get("orgId").toString();
        String refundStatus = orderInfo.get("refundStatus").toString();
        if("5".equals(refundStatus) || "6".equals(refundStatus)){
           throw GlobalException.build("该商品已退款成功，无法撤销申请！");
        }
        protectRecordService.revokeAction(orderSn, orgId, recId, 0);

        String protectCode = orderInfo.get("protectCode").toString();
        Map<String, Object> temp = new HashMap<>();
        temp.put("recId", recId);
        temp.put("protectCode", protectCode);
        temp.put("consultStatus", "买家撤销退款");
        temp.put("consultContent", "主动撤销退款，退款关闭");
        temp.put("consultImages", "");
        temp.put("consultObj", 1);
        maiBaoLaDao.addConsult(temp);
    }

    public String getRemindPhoneByGid(String gid) {
        Map<String, Object> map = maiBaoLaDao.getBelongByGoodsId(gid);
        return maiBaoLaDao.getRemindPhoneByCid(map);
    }

    /**
     * @param goodsId
     * @param customerId
     * @return 还能买几个
     */
    public Integer quota(String goodsId, String customerId) {
        if (StringUtils.isEmpty(goodsId)) {
            return -1;
        }
        Map<String, Object> goods = maiBaoLaDao.getGoodsQuotaInfoByGoodsId(goodsId);
        Integer quota = (Integer) goods.get("quota");
        Integer quotaUser = Integer.valueOf(goods.get("quotaUser").toString());
        if (quota == null || (quota == 0 && quotaUser==0)) {
            return -1;
        }
        String goodsCountKey = CrmRedisKeys.goodsCountKey + goodsId;
        String goodsCount = redisTemplate.opsForValue().get(goodsCountKey);
        if(StringUtils.isEmpty(goodsCount) || Integer.valueOf(goodsCount).equals(0)) {
            return -2;
        }
        int left = -1;
        if(quotaUser==1){
            left = -3;
            if(!StringUtils.isEmpty(goods.get("quotaLevel"))){
                String quotaLevelString = goods.get("quotaLevel").toString();
                Map quotaLevel = JSON.parseObject(quotaLevelString,Map.class);
                Integer level = 0;
                if(!StringUtils.isEmpty(quotaLevel.get("level"))){
                    level = Integer.valueOf(quotaLevel.get("level").toString());
                    if(!StringUtils.isEmpty(quotaLevel.get("quotaType"))){
                        if("1".equals(quotaLevel.get("quotaType").toString())){
                            //只看是否达到等级
                            Integer userLevel = maiBaoLaDao.getUSerLevelByCustomerId(customerId);
                            if(userLevel==null){
                                userLevel = 0;
                            }
                            if(userLevel>=level){
                                left = -1;
                            }
                        }else if("2".equals(quotaLevel.get("quotaType").toString())){
                            //看升级天数是否满足
                            Integer userLevelDay = maiBaoLaDao.getUSerLevelDayByCustomerId(customerId,level);
                            if(!StringUtils.isEmpty(quotaLevel.get("quotaDay"))){
                                Integer quotaDay = Integer.valueOf(quotaLevel.get("quotaDay").toString());
                                if(userLevelDay!=null && (userLevelDay+1)<=quotaDay){
                                    left = -1;
                                }
                            }
                        }
                    }
                }
            }
            if(!StringUtils.isEmpty(goods.get("quotaVip"))){
                if(left==-3){
                    //说明等级不符合条件继续判读vip
                    String quotaVipString = goods.get("quotaVip").toString();
                    List<Map> quotaVips= JSONArray.parseArray(quotaVipString,Map.class);

                    if(quotaVips!=null && quotaVips.size()>0){
                        for(Map quotaVip : quotaVips){
                            Long vipId = -1L;
                            if(!StringUtils.isEmpty( quotaVip.get("vipId"))){
                                vipId = Long.valueOf(quotaVip.get("vipId").toString());
                            }
                            if(!StringUtils.isEmpty(quotaVip.get("quotaType"))){
                                if("1".equals(quotaVip.get("quotaType").toString())){
                                    //只看是否达是vip
                                    Integer vipCount = maiBaoLaDao.getVipCountByCustomerId(customerId,vipId);
                                    if(vipCount!=null && vipCount>0){
                                        left = -1;
                                        break;
                                    }
                                }else if("2".equals(quotaVip.get("quotaType").toString())){
                                    //看新开通天数
                                    Integer userVipDay = maiBaoLaDao.getVipDayByCustomerId(customerId,vipId);
                                    if(!StringUtils.isEmpty(quotaVip.get("quotaDay"))){
                                        Integer quotaDay = Integer.valueOf(quotaVip.get("quotaDay").toString());
                                        if(userVipDay!=null && (userVipDay+1)<=quotaDay){
                                            left = -1;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }
        if(quota==1 && left == -1){
            //如果限购
            Integer quotaCycle = (Integer) goods.get("quotaCycle");
            Integer quotaDay = (Integer) goods.get("quotaDay");

            Map<String,Object> param = new HashMap<>();
            param.put("goodsId",goodsId);
            param.put("customerId",customerId);
            param.put("type",3);
            DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String datetime = null;
            switch (quotaCycle) {
                // 限购周期0-终身，1-日，2-周，3-月，4-近x天
                case 0:
                    // 终身
                    break;
                case 1:
                    // 日
                    datetime = LocalDate.now().format(date);
                    datetime += " 00:00:00";
//                criteria.and("datetime").gte(datetime);
                    break;
                case 2:
                    // 周
                    datetime = LocalDate.now().with(DayOfWeek.MONDAY).format(date);
                    datetime += " 00:00:00";
//                criteria.and("datetime").gte(datetime);
                    break;
                case 3:
                    // 月
                    datetime = LocalDate.now().withDayOfMonth(1).format(date);
                    datetime += " 00:00:00";
//                criteria.and("datetime").gte(datetime);
                    break;
                case 4:
                    // 近x天
                    datetime = LocalDate.now().minusDays(quotaDay).format(date);
                    datetime += " 00:00:00";
//                criteria.and("datetime").gte(datetime);
                    break;
                default:
                    break;
            }
            param.put("datetime",datetime);
            List<Map<String,Object>> mappedResults = overViewInfoDao.getGoodsBuyCount(param);
            Integer count;
            if (mappedResults != null && mappedResults.size() > 0) {
                count = Integer.valueOf(mappedResults.get(0).get("count").toString());
            } else {
                count = 0;
            }
            // 加待付款订单
            Integer unpaid = maiBaoLaDao.countUnpaidGoodsNum(goodsId, customerId);
            if (unpaid == null) {
                unpaid = 0;
            }
            count += unpaid;
            Integer quotaNum = (Integer) goods.get("quotaNum");
            left = quotaNum - count;
            if (left < 0) {
                left = 0;
            }

        }
        return left;
    }

    public Map getAppConfigurateInfo(String orgId) {
        Map map = maiBaoLaDao.getAppConfigurateInfo(orgId);
        if(map==null){
            map = new HashMap();
        }
        return map;
    }

    public void saveAppConfigurate(Map<String, Object> params,String orgId) {
        if(params.get("appId")!=null){
            Integer count = maiBaoLaDao.getAppCount(params.get("appId").toString());
            if(count==0){
                LOGGER.error("系统中不存在该app的接口地址！");
                throw GlobalException.build("该appId不正确！");
            }
        }
        Map appConfigurateInfo = maiBaoLaDao.getAppConfigurateInfo(orgId);
        if(appConfigurateInfo!=null && appConfigurateInfo.get("appId")!=null){
            maiBaoLaDao.updateAppConfigurate(params);
        }else {
            maiBaoLaDao.insertAppConfigurate(params);
        }
    }

    public Map<String, Object> getAppCustomerByCid(String customerId) {
        return maiBaoLaDao.getAppCustomerByCid(customerId);
    }

    public Integer checkOldPhone(String phone, String orgId){
        return maiBaoLaDao.checkOldPhone(phone,orgId);
    }

    public String getAliasByLinker() {
        String alias = maiBaoLaDao.getAliasByLinker();
        if (StringUtils.isEmpty(alias)) {
            throw GlobalException.build("请先设置Linker应用别名");
        }
        return alias;
    }

    public List<Map<String, Object>> getRefundInfoList(Integer recId) {
        return maiBaoLaDao.getRefundInfoList(recId);
    }

    public String getBindPhoneByCustomerId(String customerId) {
        return maiBaoLaDao.getBindPhoneByCustomerId(customerId);
    }

    public Map getSecGoodsLimit(String customerId, String goodsId, String orgId) {
        //如果是则判断是否在有效期和是否是在会员等级区间
        Map seckillMap =  mallDao.getSeckillByGoodsId(goodsId);
        String msg = "";
        Integer type = 1;
        try {
            if(seckillMap!=null){
                Integer vipLimitStart = 0;
                if(!StringUtils.isEmpty(seckillMap.get("vipLimitStart"))){
                    vipLimitStart =Integer.valueOf(seckillMap.get("vipLimitStart").toString());
                }
                Integer viPlimitEnd = 9;
                if(!StringUtils.isEmpty(seckillMap.get("viPlimitEnd"))){
                    viPlimitEnd =Integer.valueOf(seckillMap.get("viPlimitEnd").toString());
                }
                //判断会员等级(0-9不用判断)
                if(vipLimitStart>0 || viPlimitEnd<9){
                    //获取当前用户等级
                    Integer vipLevel = mallDao.getVipLevel(customerId);
                    if(vipLevel>viPlimitEnd || vipLevel<vipLimitStart){
                        msg = "会员等级必须在VIP"+vipLimitStart+"与VIP"+viPlimitEnd+"之间";
                        type = 2;
                    }
                }
                String vipIds = "";
                if(!StringUtils.isEmpty(seckillMap.get("vipIds"))){
                    vipIds = seckillMap.get("vipIds").toString();
                    Integer vipIdsCount = mallDao.getVipIdCount(customerId,vipIds);
                    if(vipIdsCount==0){
                        String vipName = mallDao.getVipName(vipIds);
                        msg = "未开通权益卡"+vipName;
                        type = 3;
                    }

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        Map resMap = new HashMap();
        resMap.put("msg",msg);
        resMap.put("type",type);
        return resMap;
    }
}
